<template>
    <div class="records-container">
        <!-- 搜索区域 -->
        <div class="search-area">
            <div class="search-item">
                <span class="label">群:</span>
                <el-select v-model="searchForm.groupId" placeholder="请选择群组" class="search-input" clearable>
                    <div v-if="groupList.length === 0" class="el-select-dropdown__item">加载群组中...</div>
                    <el-option v-for="group in groupList" :key="group.groupId" :label="group.name || group.title"
                        :value="group.groupId" />
                </el-select>
                <span v-if="debug" class="debug-info">已加载 {{ groupList.length }} 个群组</span>
            </div>
            <div class="search-item">
                <span class="label">群员昵称:</span>
                <el-input v-model="searchForm.nickname" placeholder="请输入群员昵称" class="search-input" clearable />
            </div>
            <div class="search-item">
                <span class="label">群员用户名:</span>
                <el-input v-model="searchForm.username" placeholder="请输入群员用户名" class="search-input" clearable />
            </div>
            <div class="search-item">
                <span class="label">群员id:</span>
                <el-input v-model="searchForm.userId" placeholder="请输入群员id" class="search-input" clearable />
            </div>
            <div class="search-item">
                <span class="label">活动ID:</span>
                <el-input v-model="searchForm.activityId" placeholder="请输入活动ID" class="search-input" clearable />
            </div>
            <el-button type="primary" :icon="Search" class="search-btn" @click="handleSearch"
                :loading="loading">查找</el-button>
        </div>

        <!-- 表格区域 -->
        <el-table :data="recordsList" style="width: 100%" @selection-change="handleSelectionChange"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'normal' }" v-loading="loading">
            <el-table-column type="selection" width="45" />
            <el-table-column prop="activityId" label="活动id" width="220" show-overflow-tooltip />
            <el-table-column prop="group" label="群" min-width="150">
                <template #default="scope">
                    <span>{{ scope.row.group || getGroupName(scope.row.groupId) || '未知群组' }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="member" label="群员" min-width="150" />
            <el-table-column prop="username" label="群员用户名" min-width="150" />
            <el-table-column prop="userId" label="群员id" min-width="120" />
            <el-table-column prop="points" label="消耗积分" width="100" align="center" />
            <el-table-column prop="isWinner" label="是否中奖" width="100" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.isWinner ? 'success' : 'info'" class="status-tag">
                        {{ scope.row.isWinner ? '是' : '否' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="创建时间" width="180" />
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container" v-if="total > 0">
            <span class="total-text">共 {{ total }} 条</span>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[20, 50, 100]"
                layout="prev, pager, next, sizes" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" background class="custom-pagination" />
        </div>

        <!-- 无数据提示 -->
        <div class="no-data" v-if="total === 0 && !loading">
            <el-empty description="暂无抽奖记录" />
        </div>
    </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { getLotteryRecords } from '@/api/lottery'
import { getGroupList } from '@/api/group'

export default {
    name: 'Records',
    setup() {
        const debug = ref(true); // 开发阶段设为true，生产环境可设为false

        // 搜索表单
        const searchForm = reactive({
            groupId: '',
            nickname: '',
            username: '',
            userId: '',
            activityId: ''
        })

        // 数据列表
        const recordsList = ref([])
        const groupList = ref([])
        const loading = ref(false)

        const currentPage = ref(1)
        const pageSize = ref(20)
        const total = ref(0)

        // 获取群组列表
        const fetchGroups = async () => {
            try {
                console.log('开始获取群组列表...');
                const response = await getGroupList();
                console.log('群组列表原始响应:', response);

                // 在控制台显示群组详细数据，便于调试
                if (response && response.data) {
                    console.log('群组数据内容:', JSON.stringify(response.data).substring(0, 500) + '...');
                }

                if (response && response.data) {
                    // 检查返回数据结构
                    if (Array.isArray(response.data)) {
                        groupList.value = response.data;
                        console.log('群组列表加载成功(数组):', groupList.value.length, '个群组');
                    } else if (response.data.data && Array.isArray(response.data.data)) {
                        // 如果数据嵌套在data字段中
                        groupList.value = response.data.data;
                        console.log('群组列表加载成功(嵌套):', groupList.value.length, '个群组');
                    } else if (typeof response.data === 'object') {
                        // 如果返回的是对象而非数组，尝试转换
                        const groups = [];
                        for (const key in response.data) {
                            if (Object.prototype.hasOwnProperty.call(response.data, key)) {
                                const group = response.data[key];
                                if (group.groupId) {
                                    groups.push(group);
                                }
                            }
                        }
                        groupList.value = groups;
                        console.log('群组列表加载成功(对象转换):', groupList.value.length, '个群组');
                    } else {
                        console.warn('群组数据结构异常:', response.data);
                        groupList.value = [];
                    }
                } else {
                    console.warn('获取群组列表失败: 响应为空');
                    groupList.value = [];
                }

                // 打印群组列表第一项作为样本
                if (groupList.value.length > 0) {
                    console.log('群组样本数据:', JSON.stringify(groupList.value[0]));
                }
            } catch (error) {
                console.error('获取群组列表失败:', error);
                ElMessage.error('获取群组列表失败');
                groupList.value = [];
            }
        };

        // 获取抽奖记录
        const fetchRecords = async () => {
            loading.value = true;
            try {
                const params = {
                    page: currentPage.value,
                    limit: pageSize.value,
                    ...searchForm
                };

                const response = await getLotteryRecords(params);
                console.log('获取到的抽奖记录数据:', response);

                // 正确访问嵌套数据结构
                if (response && response.data && response.data.data) {
                    recordsList.value = response.data.data.list || [];
                    total.value = response.data.data.pagination?.total || 0;
                } else {
                    // 处理异常情况
                    console.warn('响应数据结构不符合预期:', response);
                    recordsList.value = [];
                    total.value = 0;
                }
            } catch (error) {
                console.error('获取抽奖记录失败:', error);
                if (error.response && error.response.data && error.response.data.message) {
                    ElMessage.error(error.response.data.message);
                } else {
                    ElMessage.error('获取抽奖记录失败，请稍后重试');
                }
                // 出错时显示空记录
                recordsList.value = [];
                total.value = 0;
            } finally {
                loading.value = false;
            }
        };

        // 搜索
        const handleSearch = () => {
            currentPage.value = 1; // 重置为第一页
            fetchRecords();
        };

        const handleSelectionChange = (selection) => {
            console.log('选中的行:', selection);
        };

        const handleSizeChange = (val) => {
            pageSize.value = val;
            fetchRecords();
        };

        const handleCurrentChange = (val) => {
            currentPage.value = val;
            fetchRecords();
        };

        // 根据群组ID查找群组名称
        const getGroupName = (groupId) => {
            if (!groupId) return '';
            const group = groupList.value.find(g => g.groupId === groupId);
            return group ? (group.name || group.title || group.groupName) : '';
        };

        onMounted(() => {
            fetchGroups();
            fetchRecords();
        });

        return {
            searchForm,
            recordsList,
            groupList,
            currentPage,
            pageSize,
            total,
            loading,
            Search,
            handleSearch,
            handleSelectionChange,
            handleSizeChange,
            handleCurrentChange,
            getGroupName,
            debug,
        };
    }
};
</script>

<style scoped>
.records-container {
    background-color: #fff;
    border-radius: 2px;
    padding: 15px;
}

.search-area {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 15px;
    flex-wrap: wrap;
}

.search-item {
    display: flex;
    align-items: center;
}

.label {
    font-size: 13px;
    color: #606266;
    margin-right: 8px;
}

.search-input {
    width: 180px;
}

.search-btn {
    height: 32px;
    padding: 0 15px;
    font-size: 13px;
}

.pagination-container {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.total-text {
    margin-right: 12px;
    color: #606266;
    font-size: 13px;
}

.no-data {
    margin-top: 40px;
    display: flex;
    justify-content: center;
}

:deep(.el-table) {
    --el-table-border-color: #ebeef5;
    font-size: 13px;
}

:deep(.el-table th) {
    font-weight: normal;
    height: 40px;
    padding: 8px 0;
}

:deep(.el-table td) {
    padding: 8px 0;
}

:deep(.el-checkbox__inner) {
    width: 14px;
    height: 14px;
}

:deep(.status-tag) {
    height: 22px;
    padding: 0 8px;
    font-size: 12px;
}

:deep(.el-pagination) {
    font-size: 13px;
}

:deep(.el-pagination .el-select .el-input) {
    width: 100px;
}

:deep(.el-pagination button) {
    min-width: 28px;
    height: 28px;
}

:deep(.el-pagination .el-select .el-input__inner) {
    height: 28px;
}

:deep(.el-button--primary) {
    --el-button-bg-color: #1890ff;
    --el-button-border-color: #1890ff;
    --el-button-hover-bg-color: #40a9ff;
    --el-button-hover-border-color: #40a9ff;
}

:deep(.el-input__inner) {
    height: 32px;
}

:deep(.el-select__caret) {
    height: 32px;
    line-height: 32px;
}
</style>